package caidan.net;

import jinyilw.swing.visuals.window.HintWindow;
import jinyilw.tools.h2db.DBConfig;
import jinyilw.tools.net.ServerTools;
import jinyilw.tools.net.dev.BaseClient;
import jinyilw.tools.net.dev.CommandPacket;
import jinyilw.tools.net.dev.NetworkPacket;

import java.util.List;

public class AdminSuggestPanel extends AbstractSuggestPanel
{
	private static final long serialVersionUID = -8424692830726670977L;
	// private static File suggestFile = FileTools.openFile(".data/suggest");
	private ServerTools serverTools;

	public AdminSuggestPanel(ServerTools tools)
	{
		serverTools = tools;
	}

	@Override
	public void initNet()
	{
		jdbcTools = DBConfig.getDefaultTools();
		isConnected = jdbcTools.isConnected();
		serverTools.addReceiveClientPacketOperator((BaseClient c) ->
		{
			for (NetworkPacket packets : c.getReceivedPackets())
			{
				if (packets instanceof CommandPacket)
				{
					CommandPacket packet = (CommandPacket) packets;
					if (Command.freshSuggest == packet.getCommandID())
						new Thread(() ->
						{
							reloadDatabase();
						}).start();
				}
			}
		});
		reloadDatabase();
	}

	@Override
	public synchronized void reloadDatabase()
	{
		isConnected = jdbcTools.isConnected();
		if (!isConnected)
			return;
		int bsize = contentPanel.getComponentCount();
		contentPanel.removeAll();
		readFromDatabase();
		readFromAdminDatabase();
		revalidate();
		repaint();

		int asize = contentPanel.getComponentCount();
		if (bsize > asize)
			for (int i = bsize - 1; i >= asize; i--)
				suggestLabels.remove(i);
	}

	@Override
	protected void readFromDatabase()
	{
		if (!isConnected)
			return;
		List<Suggest> suggestList = null;
		try
		{
			suggestList = jdbcTools.findMoreRefResult("select * from suggest",
					Suggest.class);
		} catch (Exception e)
		{
			e.printStackTrace();
			return;
		}
		int i = contentPanel.getComponentCount(), size = suggestLabels.size();
		SuggestLabel label;
		if (suggestList != null)
			for (Suggest suggest : suggestList)
			{
				if (i < size)
				{
					label = suggestLabels.get(i);
					label.setLabel(suggest, true, false);
					i++;
				} else
				{
					label = new SuggestLabel(suggest, true);
					suggestLabels.add(label);
				}
				contentPanel.add(label);
			}
	}

	void readFromAdminDatabase()
	{
		if (!isConnected)
			return;
		List<Suggest> suggestList = null;
		try
		{
			suggestList = jdbcTools.findMoreRefResult(
					"select * from adminSuggest", Suggest.class);
		} catch (Exception e)
		{
			e.printStackTrace();
			return;
		}
		int i = contentPanel.getComponentCount(), size = suggestLabels.size();
		SuggestLabel label;
		if (suggestList != null)
			for (Suggest suggest : suggestList)
			{
				if (i < size)
				{
					label = suggestLabels.get(i);
					label.setLabel(suggest, false, false);
					i++;
				} else
				{
					label = new SuggestLabel(suggest);
					suggestLabels.add(label);
				}
				contentPanel.add(label);
			}
	}

	//	public void readFromFile()
	//	{
	//		if (suggestFile == null || !suggestFile.exists())
	//			return;
	//		DataInputStream dis = null;
	//		boolean isNet, isSend;
	//		String user, content, dateString;
	//		Suggest suggest;
	//		SuggestLabel label;
	//		try
	//		{
	//			dis = new DataInputStream(new FileInputStream(suggestFile));
	//			int length = dis.readInt();
	//			for (int j = 0; j < length; j++)
	//			{
	//				isNet = dis.readBoolean();
	//				isSend = dis.readBoolean();
	//				user = dis.readUTF();
	//				content = dis.readUTF();
	//				dateString = dis.readUTF();
	//				if (isConnected && isNet)
	//					continue;
	//				suggest = new Suggest(user, content, dateString);
	//				label = new SuggestLabel(suggest, isNet, isSend);
	//				suContentPanel.add(label);
	//				if (isNet)
	//					suggestLabels.add(label);
	//				else
	//					localLabels.add(label);
	//			}
	//			dis.close();
	//		} catch (Exception e)
	//		{
	//			e.printStackTrace();
	//			try
	//			{
	//				if (dis != null)
	//					dis.close();
	//			} catch (IOException e1)
	//			{
	//				e1.printStackTrace();
	//			}
	//		}
	//	}
	//
	//	public void writeToFile()
	//	{
	//		DataOutputStream dos = null;
	//		try
	//		{
	//			dos = new DataOutputStream(new FileOutputStream(suggestFile));
	//			dos.writeInt(suggestLabels.size() + localLabels.size());
	//			for (SuggestLabel label : suggestLabels)
	//				label.writeData(dos);
	//			for (SuggestLabel label : localLabels)
	//				label.writeData(dos);
	//			dos.close();
	//		} catch (Exception e)
	//		{
	//			e.printStackTrace();
	//			try
	//			{
	//				if (dos != null)
	//					dos.close();
	//			} catch (IOException e1)
	//			{
	//				e1.printStackTrace();
	//			}
	//		}
	//	}

	@Override
	public void removeSuggestLabel(SuggestLabel label)
	{
		contentPanel.remove(label);
		revalidate();
		repaint();
		suggestLabels.remove(label);
		adminDeleteSuggest(label.suggest, label.isNet);
	}

	@Override
	public void addSuggestLabel(SuggestLabel label)
	{
		contentPanel.add(label);
		revalidate();
		repaint();
		suggestLabels.add(label);
	}

	public void adminDeleteSuggest(Suggest suggest, boolean isNet)
	{
		String sql = isNet
				? "delete from suggest where id = ?"
				: "delete from adminSuggest where id = ?";
		boolean ok = jdbcTools.updateByPreparedStatement(sql, suggest.getId());
		if (isNet && ok)
			broadcastCommand(new CommandPacket(Command.freshSuggest, true));
	}

	public boolean sendSuggestToNet(Suggest suggest)
	{
		String sql = "insert into suggest(user,content,dateString) values(?,?,?)";
		boolean ok = jdbcTools.updateByPreparedStatement(sql, suggest.getUser(),
				suggest.getContent(), suggest.getDateString());
		if (ok)
			broadcastCommand(new CommandPacket(Command.freshSuggest, true));
		return ok;
	}

	public void broadcastCommand(CommandPacket commandPacket)
	{
		serverTools.broadcastCommand(commandPacket);
	}

	@Override
	public boolean isClient()
	{
		return false;
	}

	@Override
	public void sendSuggest(SuggestLabel suggestLabel)
	{
		if (sendSuggestToNet(suggestLabel.suggest))
		{
			adminDeleteSuggest(suggestLabel.suggest, false);
			reloadDatabase();
		} else
			HintWindow.showHint("发送失败！", getParent());
	}

	//	class SuggestLabel extends WrapLabel
	//	{
	//		private static final long serialVersionUID = 6135927525395642839L;
	//		private Suggest suggest;
	//		private boolean isNet, isSend;
	//		private JActImageComp sendLabel;
	//		private RichTitleBorder titleBorder = new RichTitleBorder(null,
	//				FontTools.defaultFont);
	//		private RoundIconButton closeButton = new RoundIconButton(
	//				Resource.closeIcon);
	//
	//		public SuggestLabel(Suggest suggest)
	//		{
	//			this(suggest, false);
	//		}
	//
	//		public SuggestLabel(Suggest suggest, boolean isNet)
	//		{
	//			this(suggest, isNet, false);
	//		}
	//
	//		public SuggestLabel(Suggest suggest, boolean isNet, boolean isSend)
	//		{
	//			setWrapWidth(suggestWidth);
	//			setFont(suggestFont);
	//			setBorder(titleBorder);
	//			closeButton.addClickOperater((Object o) ->
	//			{
	//				removeSuggestLabel(SuggestLabel.this);
	//			});
	//			SwingTools.addTitleComponents(this, closeButton);
	//			setLabel(suggest, isNet, isSend);
	//		}
	//
	//		public void setLabel(Suggest suggest, boolean isNet, boolean isSend)
	//		{
	//			this.suggest = suggest;
	//			this.isNet = isNet;
	//			this.isSend = isSend;
	//			String title = suggest.getTitle();
	//			if (isNet)
	//				title += "-已推送";
	//			else
	//				title += "-未推送";
	//			titleBorder.setTitle(title);
	//			setText("      " + suggest.getContent());
	//			if (isNet)
	//			{
	//				if (sendLabel != null)
	//					remove(sendLabel);
	//			} else
	//			{
	//				if (sendLabel == null)
	//				{
	//					sendLabel = new JActImageComp(Resource.sendIcon);
	//					sendLabel.addClickOperater((Object o) ->
	//					{
	//						sendSuggest();
	//					});
	//				}
	//				SwingTools.addTitleComponents(this, sendLabel);
	//				if (isSend)
	//				{
	//					sendLabel.setToolTipText("已发送");
	//					sendLabel.setEnabled(false);
	//				} else
	//				{
	//					sendLabel.setToolTipText("发送到网络");
	//					sendLabel.setEnabled(true);
	//				}
	//			}
	//		}
	//
	//		public void sendSuggest()
	//		{
	//			if (sendSuggestToNet(suggest))
	//			{
	//				adminDeleteSuggest(suggest, false);
	//				reLoadDatabase();
	////				isSend = true;
	////				sendLabel.setEnabled(false);
	////				HintWindow.showHint("已发送到网络！", getParent());
	////				sendLabel.setToolTipText("已发送");
	//			} else
	//				HintWindow.showHint("发送失败！", getParent());
	//		}
	//
	//		public void writeData(DataOutputStream dos)
	//		{
	//			try
	//			{
	//				dos.writeBoolean(isNet);
	//				dos.writeBoolean(isSend);
	//				dos.writeUTF(suggest.getUser());
	//				dos.writeUTF(suggest.getContent());
	//				dos.writeUTF(suggest.getDateString());
	//			} catch (IOException e)
	//			{
	//				e.printStackTrace();
	//			}
	//		}
	//		@Override
	//		public Dimension getPreferredSize()
	//		{
	//			Dimension dim = super.getPreferredSize();
	//			if (dim.width < suggestWidth - 5)
	//				dim.width = suggestWidth - 5;
	//			return dim;
	//		}
	//	}
}
